﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Jermaine.Serialization
{
    public class ObjectSerializer : AbstractSerializer, ISerializer
    {

        public ObjectSerializer() : base() { }


        /// <summary>
        /// Serialize objects to binary file
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="o"></param>
        public void Serialize<T>(string path, T o) where T : new() {
            base.IsNull(o);

            using (var stream = new FileStream(path, FileMode.Create)) {
                var f = new BinaryFormatter();
                f.Serialize(stream, o);
            }


        }



        /// <summary>
        /// Deserialize the binary file to objects
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public T Deserailize<T>(string path) {
            base.PathExists(path);

            using (var stream = new FileStream(path, FileMode.Open)) {
                var f = new BinaryFormatter();
                return (T)f.Deserialize(stream);
            }

        }


        public string Format<T>(T o) {

            using (var stream = new MemoryStream()) {
                var f = new BinaryFormatter();
                f.Serialize(stream, o);
                return Encoding.Default.GetString(stream.ToArray());

            }


        }

        public T Parse<T>(string stringObject) {

            var bytes = Encoding.Default.GetBytes(stringObject);
            using (var stream = new MemoryStream(bytes)) {
                var f = new BinaryFormatter();
                return (T)f.Deserialize(stream);

            }

        }
    }
}
